<?php
/**
 * Finance
 */
class controller_finance extends controller_base {
	/**
	 * index
	 */
	public function action_index() {
		echo 'Welecome to Finance<hr />';
	}
	
	/**
	 * payout list
	 */
	public function action_pay_list() {
		// 指定ID, 支持多个
		if(!empty($_GET['id'])) {
			preg_match_all('/\d+/', $_GET['id'], $matches);
			$ids = isset($matches[0]) ? $matches[0] : array();
			$where = 'not_id IN ('.implode(',', $ids).')';
		// 指定天数, 支持段
		} elseif (!empty($_GET['day'])) {
			$days = explode(',', $_GET['day']);
			$start_day = isset($days[0]) ? intval($days[0]) : 1;
			$limit_day = isset($days[1]) ? intval($days[1]) : 0;

			$start_time = strtotime(date('Y-m-d')) - ($start_day - 1) * 86400;
			$end_time = $limit_day ? $start_time + $limit_day * 86400 : 0;

			$where = 'create_time >= '.$start_time;
			$end_time > 0 && $where .= ' AND create_time < '.$end_time;
		// 指定日期，支持段
		} elseif (!empty($_GET['date'])) {
			$dates = explode(',', $_GET['date']);	
			$start_time = isset($dates[0]) ? strtotime($dates[0]) : strtotime(date('Y-m-d'));	
			$end_time = isset($dates[1]) ? strtotime($dates[1]) + 86400 : $start_time + 86400;

			$where = 'create_time >= '.$start_time.' AND create_time < '.$end_time;
		// 查看全部
		} elseif (isset($_GET['all'])) {
			$where = '1';
		// 默认
		} else {
			$where = 'create_time >= '.(strtotime(date('Y-m-d')) - 29 * 86400);
		}

		// 关键字搜索
		if(isset($_GET['key'])) {
			$key = trim(addslashes($_GET['key']));
			$where .= " AND pay_name LIKE '%$key%'";
		}

		$model_payout = new model_payout();
		$model_note = new model_note();
		
		//模板赋值
		$this->assign('daily_data', $model_payout->get_daily_data($where));
		$this->assign('sum', $model_payout->get_sum());
		$this->assign('sum_limit', $model_payout->get_sum(300));
		$this->assign('sum_30', $model_payout->get_sum_30());
		$this->assign('sum_30_limit', $model_payout->get_sum_30(300));
		$this->assign('pay_range', $model_payout->get_range());
		$this->assign('notes', $model_note->get_notes('rank=8'));	// 线上用

        $this->assign('title', '出账列表');
	}
	
	/**
	 * payout add
	 */
	public function action_pay_add() {
		if(empty($_POST['pay_name']) == false) {
			//add do
			$model_payout = new model_payout();
			$data = array();
			$data = $_POST;
			$data['create_time'] = library_common::str2date($data['create_time']);
			$model_payout->create($data);
			
			//添加日志
			$model_payout->log_write('pay_add '.print_r($data, 1));
			
			$this->message('添加成功', '?m=finance&a=pay_list');
		} else {
			//form
            $this->assign('title', '添加出账');
		}
	}

    public function action_mobile_pay_add() {
        
    }
	
	/**
	 * payout edit
	 */
	public function action_pay_edit() {
		if(empty($_POST['pay_name']) == false) {
			//edit do
			$model_payout = new model_payout();
			//记录原数据
			$data_old = $model_payout->find('pay_id='.$_POST['pay_id']);
			//修改
			$data = array();
			$data = $_POST;
			$data['create_time'] = library_common::str2date($data['create_time']);
			$model_payout->update($data);
			
			//添加日志
			$model_payout->log_write('pay_edit '.print_r($data_old, 1).' >>>> '.print_r($data, 1));
			
			$this->message('修改成功', '?m=finance&a=pay_list');
		} else {
			//edit form
			$model_payout = new model_payout();
			$pay_id = $_GET['pay_id'];
			
			$res = $model_payout->find("pay_id='$pay_id'");
			$this->assign('res', $res);
            $this->assign('title', '修改出账');
		}
	}
	
	/**
	 * payout delete
	 */
	public function action_pay_delete() {
		$pay_id = $_GET['pay_id'];
		$model_payout = new model_payout();
		//记录
		$data = $model_payout->find("pay_id='$pay_id'");
		//删除
		$model_payout->delete("pay_id='$pay_id'");
		
		//添加日志
		$model_payout->log_write('pay_del '.print_r($data, 1));
		
		$this->message('删除成功', '?m=finance&a=pay_list');
	}
	
	/**
	 * payout 图表1
	 */
	public function action_pay_chart() {
		$model_payout = new model_payout();
		$daily_stat = $model_payout->get_daily_stat();
		$daily_stat_lite = $model_payout->get_daily_stat('amount < 300');
		
		$this->assign('daily_stat', $daily_stat);
		$this->assign('daily_stat_lite', $daily_stat_lite);
        $this->assign('title', '出账图表');
	}
	
	/**
	 * payout 图表2
	 */
	public function action_pay_chart2() {
		$model_payout = new model_payout();
		
		$this->assign('p', $model_payout);
        $this->assign('title', '出账图表2');
	}
	
	/**
	 * payout 分析
	 */
	public function action_pay_analytics() {
		// 获取时间
		$start_time = isset($_GET['start_time']) ? $_GET['start_time'] : date('Y-m-d', time() - 86400 * 29);
		$end_time = isset($_GET['end_time']) ? $_GET['end_time'] : date('Y-m-d');
		
		// 转换时间格式
		$start_time = strtotime($start_time);
		$end_time = strtotime($end_time);
		
		// 查询数据
		$model_payout = new model_payout();
		$result = $model_payout->find_all("create_time BETWEEN $start_time AND $end_time", 'amount DESC, create_time DESC');
		
		// 整理数据
		$data = array();
		$sum_all = 0;
		foreach ($result as $row) {
			if($row['amount'] >= 300) {
				$data['300'][] = $row;
			} elseif ($row['amount'] >= 100 ) {
				$data['100'][] = $row;		
			} elseif ($row['amount'] >= 50) {
				$data['50'][] = $row;
			} elseif ($row['amount'] >= 10) {
				$data['10'][] = $row;
			} else {
				$data['0'][] = $row;
			}
			$sum_all += $row['amount'];
		}
		
		$this->assign('data', $data);
		$this->assign('sum_all', $sum_all);
		$this->assign('start_time', $start_time);
		$this->assign('end_time', $end_time);
        $this->assign('title', '出账分析');
	}
	
	/**
	 * income 列表
	 */
	public function action_inc_list() {
		$model_income = new model_income();
		
		$result = $model_income->find_all(1, 'create_time DESC');
		$income_by_mouth = array();
		foreach ($result as $row) {
			$income_by_mouth[date('Ym', $row['create_time'])][] = $row;
		}
		
		$sum = $model_income->find(1, '', '', 'SUM(amount) total');
		
		$this->assign('income_by_mouth', $income_by_mouth);	
		$this->assign('sum', $sum['total']);	
        $this->assign('title', '入账列表');
	}
	
	/**
	 * income 添加
	 */
	public function action_inc_add() {
		if(empty($_POST['inc_name']) == false) {
			//add do
			$model_income = new model_income();
			$data = array();
			$data = $_POST;
			$data['create_time'] = library_common::str2date($data['create_time']);
			$model_income->create($data);
			
			//添加日志
			new model_logs('income add - '.print_r($data, 1));
			
			$this->message('添加成功', '?m=finance&a=inc_list');
		} else {
			//form
            $this->assign('title', '添加入账');
		}
	}
	
	/**
	 * income 修改
	 */
	public function action_inc_edit() {
		if(empty($_POST['inc_name']) == false) {
			//edit do
			$model_income = new model_income();
			//记录原数据
			$data_old = $model_income->find('inc_id='.$_POST['inc_id']);
			//修改
			$data = array();
			$data = $_POST;
			$data['create_time'] = library_common::str2date($data['create_time']);
			$model_income->update($data);
			
			//添加日志
			new model_logs('inc_edit '.print_r($data_old, 1).' >>>> '.print_r($data, 1));
			
			$this->message('修改成功', '?m=finance&a=inc_list');
		} else {
			//edit form
			$model_income = new model_income();
			$inc_id = $_GET['inc_id'];
			
			$res = $model_income->find("inc_id='$inc_id'");
			$this->assign('res', $res);
            $this->assign('title', '修改入账');
		}
	}
	
	/**
	 * income 删除
	 */
	public function action_inc_delete() {
		$inc_id = $_GET['inc_id'];
		$model_income = new model_income();
		//记录
		$data = $model_income->find("inc_id='$inc_id'");
		//删除
		$model_income->delete("inc_id='$inc_id'");
		
		//添加日志
		new model_logs('inc_delete '.print_r($data, 1));
		
		$this->message('删除成功', '?m=finance&a=inc_list');
	}
	
	/**
	 * audit list
	 */
	public function action_aud_list() {
		$model_audit = new model_audit();
		$model_payout = new model_payout();
		
		$res = $model_audit->find_all(1, 'create_time DESC');
		
		$audit_last = $model_audit->get_last();
		$last_time = strtotime(date('Y-m-d', $audit_last['create_time']));
		
		// 入账
		$model_income = new model_income();
		$income_sum = $model_income->find("create_time >= $last_time", '', 1, 'SUM(amount) sum');
		
		$this->assign('res', $res);
		$this->assign('audit_last', $audit_last);
		$this->assign('payout_last', $model_payout->get_sum_by_time($last_time));
		$this->assign('income_last', $income_sum['sum']);
        $this->assign('title', '审计');
	}
	
	/**
	 * audit form
	 */
	public function action_aud_form() {
		$do = empty($_GET['aud_id']) ? 'add' : 'edit';
		$res = array(
			'amount' => '',
			'note' => '',
		);
		if(!empty($_GET['aud_id'])) {
			$model_audit = new model_audit();
			$res = $model_audit->find("aud_id='{$_GET['aud_id']}'");
		}
		
		$this->assign('res', $res);
		$this->assign('do', $do);
		$this->assign('title', '添加审计');
	}
	
	/**
	 * audit delete
	 */
	public function action_aud_delete() {
		$model_audit = new model_audit();
		//取原数据
		$res = $model_audit->find("aud_id='{$_GET['aud_id']}'");
		//删除
		$model_audit->delete("aud_id='{$_GET['aud_id']}'");
		
		//添加日志
		new model_logs('audit delete - '.print_r($res, 1));
		
		$this->message('删除成功', '?m=finance&a=aud_list');
	}
	
	/**
	 * audit add
	 */
	public function action_aud_add() {
		$model_audit = new model_audit();

		$data = array(
			'amount' => $_POST['amount'],
			'note' => $_POST['note'],
			'create_time' => time(),
		);
		$model_audit->create($data);
		
		//添加日志
		new model_logs('audit add - '.print_r($data, 1));
		
		$this->message('添加成功', '?m=finance&a=aud_list');
	}
	
	/**
	 * audit edit
	 */
	public function action_aud_edit() {
		$model_audit = new model_audit();
		$data_old = $model_audit->find('aud_id='.$_POST['aud_id']);
		$data = array(
			'aud_id' => $_POST['aud_id'],
			'amount' => $_POST['amount'],
			'note' => $_POST['note'],
		);
		$model_audit->update($data);
		
		//添加日志
		new model_logs('audit add - '.print_r($data_old, 1).' >>>> '.print_r($data, 1));
		
		$this->message('保存成功', '?m=finance&a=aud_list');
	}

    //--------------------------------------------------------------------------
    // Assets
    //--------------------------------------------------------------------------

	/**
	 * Assets list
	 */
	public function action_assets_list() {
		$modelAssets = new common_model(array(), 'assets', 'id');
                
                $sql = 'SELECT a2.id,a2.name,a2.amount,MAX(a2.createtime) maxcreatetime,createtime FROM (SELECT * FROM '.DB_PREFIX.'assets a ORDER BY a.createtime DESC) a2 GROUP BY a2.name';
                $resLast = $modelAssets->query_db($sql);
                
                $lastIds = array();
                $lastSum = 0;
          	foreach ($resLast as $item) {
          		$lastIds[$item['id']] = $item;
                        $lastSum += $item['amount'];
         	}
                
		$res = $modelAssets->find_all(1, 'createtime DESC');
		
		$this->assign('res', $res);
                $this->assign('resLast', $resLast);
                $this->assign('lastIds', $lastIds);
                $this->assign('lastSum', $lastSum);
                $this->assign('title', 'Assets');
	}
	
	/**
	 * Assets Form
	 */
	public function action_assets_form() {
		$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

        $res = array();

		if($id !== 0)
        {
            $modelAssets = new common_model(array(), 'assets', 'id');
            $res = $modelAssets->find("id=$id");
        }

		$this->assign('res', $res);
		$this->assign('title', 'Assest Edit');
	}
	
	/**
	 * Assets Delete
	 */
	public function action_assets_delete() {
		$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

        $modelAssets = new common_model(array(), 'assets', 'id');

		//取原数据
		$res = $modelAssets->find("id=$id");

		//删除
		$modelAssets->delete("id=$id");
		
		//添加日志
		new model_logs('Assets Delete - '.print_r($res, 1));
		
		$this->message('删除成功', '?m=finance&a=assets_list');
	}
	
	/**
	 * Assets Add
	 */
	public function action_assets_add() {
        $modelAssets = new common_model(array(), 'assets', 'id');

		$data = array(
			'name' => trim($_POST['name']),
			'amount' => $_POST['amount'],
			'note' => $_POST['note'],
			'createtime' => time(),
		);

		$modelAssets->create($data);
		
		//添加日志
		new model_logs('Assets Add - '.print_r($data, 1));
		
		$this->message('添加成功', '?m=finance&a=assets_list');
	}
	
	/**
	 * Assets Edit
	 */
	public function action_assets_edit() {
		$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

        if ($id === 0)
        {
            $this->message('参数错误', '?m=finance&a=assets_list');
        }

        $modelAssets = new common_model(array(), 'assets', 'id');

		$dataOld = $modelAssets->find("id=$id");

		$data = array(
			'id' => $id,
            'name' => trim($_POST['name']),
			'amount' => $_POST['amount'],
			'note' => $_POST['note'],
		);

		$modelAssets->update($data);
		
		//添加日志
		new model_logs('Assets Add - '.print_r($dataOld, 1).' >>>> '.print_r($data, 1));
		
		$this->message('保存成功', '?m=finance&a=assets_list');
	}

}